package com.example.e_comm.controller;

import com.example.e_comm.entity.User;
import com.example.e_comm.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    // 您的其他方法保持不变...
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        try {
            boolean result = userService.register(user);
            if (result) {
                logger.info("用户注册成功: {}", user.getUsername());
                return ResponseEntity.ok("注册成功");
            } else {
                logger.warn("用户注册失败: {}", user.getUsername());
                return ResponseEntity.ok("注册失败");
            }
        } catch (IllegalArgumentException e) {
            logger.error("注册时发生参数错误: {}", e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String username,
                                   @RequestParam String password) {
        try {
            String token = userService.login(username, password);
            Map<String, String> response = new HashMap<>();
            response.put("token", token);
            response.put("message", "登录成功");
            logger.info("用户登录成功: {}", username);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            logger.error("登录时发生错误 - 用户名: {}, 错误: {}", username, e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token) {
        logger.info("接收到的Token: {}", token);

        try {
            String cleanToken = token.replace("Bearer ", "");
            logger.info("清洗后的Token: {}", cleanToken);

            User user = userService.getUserByToken(cleanToken);
            if (user != null) {
                user.setPassword(null);
                logger.info("成功获取用户信息: {}", user.getUsername());
                return ResponseEntity.ok(user);
            } else {
                logger.warn("没有找到对应用户或Token已过期");
                return ResponseEntity.status(401).body("没有找到对应用户，或Token已过期");
            }
        } catch (Exception e) {
            logger.error("获取当前用户信息时发生错误: ", e);
            return ResponseEntity.status(400).body("请求错误: " + e.getMessage());
        }
    }
}